package com.tiger.admin.http.teacher;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.admin.Db;
import com.tiger.admin.SaveOperateLog;
import com.tiger.admin.dto.PaginationResult;
import com.tiger.admin.http.common.member.MemberService;
import com.tiger.admin.http.schoolDept.SchoolDeptService;
import com.tiger.admin.http.teacher.dto.PageDto;
import com.tiger.admin.http.teacher.type.TeacherRes;
import com.tiger.db.entity.OtherUser;
import com.tiger.db.entity.SchoolDept;
import com.tiger.db.entity.Teacher;
import com.tiger.utils.ResponseUtil;
import com.tiger.utils.Utils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    private final MemberService memberService;
    private final TeacherService teacherService;
    private final SchoolDeptService schoolDeptService;
    private final Db db;

    public TeacherController(MemberService memberService, TeacherService teacherService, SchoolDeptService schoolDeptService, Db db) {
        this.memberService = memberService;
        this.teacherService = teacherService;
        this.schoolDeptService = schoolDeptService;
        this.db = db;
    }
    @PostMapping("page")
    public Object page(@RequestBody PageDto page, @RequestAttribute("memberId") long memberId) {
        PaginationResult<TeacherRes> result = new PaginationResult<>();

        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Teacher::getJobStatusCode, "3");

        if(page.getName() != null && !page.getName().isEmpty()) {
            wrapper.eq(Teacher::getName, page.getName());
        }
        if(page.getGh() != null && !page.getGh().isEmpty()) {
            wrapper.eq(Teacher::getGh, page.getGh());
        }


        if(page.getDeptCode() != null && !page.getDeptCode().isEmpty()) {
            List<SchoolDept> subDepts = schoolDeptService.querySubDeptsByCode(page.getDeptCode());
            if(subDepts == null) {
                return ResponseUtil.successRes(result);
            }

            List<String> deptCodes = subDepts.stream().map(SchoolDept::getCode).collect(Collectors.toList());

            deptCodes.add(page.getDeptCode());

            if(deptCodes.size() == 1) {
                wrapper.eq(Teacher::getDeptCode, deptCodes.get(0));
            }else {
                wrapper.in(Teacher::getDeptCode, deptCodes);
            }

        }

        long total = db.teacher.count(wrapper);
        if(total > 0) {
            result.setTotal(total);

            wrapper.orderByDesc(Teacher::getId);


            List<TeacherRes> resRows = new ArrayList<>();
            List<Teacher> rows = db.teacher.pagination(wrapper, page.getPageNo(), page.getPageSize());

            List<String> deptCodes = new ArrayList<>();

            for(Teacher row : rows) {
                if(row.getTel() != null && !row.getTel().isEmpty()) {
                    row.setTel(Utils.maskMobileNumber(row.getTel()));
                }

                row.setName(Utils.maskName(row.getName()));
                row.setGh(Utils.maskUserAccount(row.getGh()));

                if(!row.getDeptCode().isEmpty()) {
                    deptCodes.add(row.getDeptCode());
                }

                TeacherRes res = new TeacherRes();
                BeanUtils.copyProperties(row, res);
                resRows.add(res);
            }

            if(!deptCodes.isEmpty()) {
                LambdaQueryWrapper<SchoolDept> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(SchoolDept::getCode, SchoolDept::getName);
                List<SchoolDept> depts = db.schoolDept.list(deptCodes.size() == 1 ? queryWrapper.eq(SchoolDept::getCode, deptCodes.get(0)) : queryWrapper.in(SchoolDept::getCode, deptCodes));

                if(!depts.isEmpty()) {
                    Map<String, String> deptMap = new HashMap<>();
                    for(SchoolDept dept : depts) {
                        deptMap.put(dept.getCode(), dept.getName());
                    }

                    for(TeacherRes row : resRows){
                        if(deptMap.containsKey(row.getDeptCode())) {
                            row.setDeptName(deptMap.get(row.getDeptCode()));
                        }
                    }
                }
            }

            result.setRows(resRows);
        }


        return ResponseUtil.successRes(result);
    }

    @SaveOperateLog("新增教职工")
    @PostMapping("add")
    public Object add(@RequestBody @Validated Teacher data, @RequestAttribute("memberId") long memberId) {
        if(db.teacher.exists(new LambdaQueryWrapper<Teacher>().eq(Teacher::getGh, data.getGh()))) {
            return ResponseUtil.failRes("已存在相同的工号");
        }

        data.setJobStatusCode("3");
        data.setSource(2);

        Instant now = Instant.now();

        data.setCreateTime(now.getEpochSecond());
        data.setSource(2);
        boolean r = db.teacher.save(data);

        return r ? ResponseUtil.successRes(data) : ResponseUtil.failRes();

    }

    @SaveOperateLog("修改教职工")
    @PostMapping("update/{id}")
    public Object add(@RequestBody @Validated Teacher data, @PathVariable Long id, @RequestAttribute("memberId") long memberId) {
        Teacher row = db.teacher.getById(id);
        if(row == null) return ResponseUtil.successRes();
        if(data.getGh() != null && !data.getGh().equals(row.getGh())) {
            if(db.teacher.exists(new LambdaQueryWrapper<Teacher>().eq(Teacher::getGh, data.getGh()))) {
                return ResponseUtil.failRes("已存在相同的工号");
            }
        }

        Instant now = Instant.now();

        Utils.copyPropertiesIgnoreNull(data, row);

        row.setUpdateTime(now.getEpochSecond());


        boolean r = db.teacher.updateById(row);

        return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();

    }

    @SaveOperateLog("删除教职工")
    @PostMapping("delete/{id}")
    public Object del(@PathVariable long id, @RequestAttribute("memberId") long memberId) {
        Teacher row = db.teacher.getOne(new QueryWrapper<Teacher>().select("id").eq("id", id));
        if(row == null) return ResponseUtil.successRes();
        boolean r = db.teacher.removeById(id);
        return r ? ResponseUtil.successRes() : ResponseUtil.failRes();
    }

    /**
     * 从学校拉取老师
     * */
    @SaveOperateLog("拉取教职工")
    @PostMapping("pull")
    public Object pull(@RequestAttribute("memberId") long memberId) {
        Instant now = Instant.now();
        //openAccountService.pullTeacher("pull:student:" + memberId + ":" + now.getEpochSecond());
        return ResponseUtil.successRes();
    }


    /**
     * 查看敏感信息
     * */
    @PostMapping("secrecy/{userId}")
    public Object secrecy(@RequestBody() HashMap<String, String> data, @PathVariable("userId") int userId, @RequestAttribute("memberId") long memberId, HttpSession session) {
        String password = data.get("password");
        String field = data.get("field");
        if(password == null || password.isEmpty()) return ResponseUtil.failRes();
        if(field == null || field.isEmpty()) return ResponseUtil.failRes();

        if(session.getAttribute(password) == null) return ResponseUtil.failRes("密码错误");

        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getId, userId);

        if(field.equals("name")) {
            wrapper.select(Teacher::getName);
        }else if(field.equals("gh")) {
            wrapper.select(Teacher::getGh);
        }else if(field.equals("tel")) {
            wrapper.select(Teacher::getTel);
        }else {
            return ResponseUtil.failRes();
        }

        Teacher teacher = db.teacher.getOne(wrapper);


        return ResponseUtil.successRes(teacher);
    }


}
